﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace PeopleEntity
{
    public class YearRangeAttribute : ValidationAttribute, IClientValidatable, IMetadataAware
    {
        public int MinYear { get; set; }

        public override bool IsValid(object value)
        {
            var date = (DateTime) value;
            return (date.Year > MinYear && date.Year < DateTime.Now.Year);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessage,
                ValidationType = "rangeyearvalidation"
            };
            rule.ValidationParameters["mindate"] = MinYear;
            rule.ValidationParameters["maxdate"] = DateTime.Now.Year;
            yield return rule;
        }

        public void OnMetadataCreated(ModelMetadata metadata)
        {
            metadata.DataTypeName = "Date";
        }
    }
}
